#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "minidb.h"

void usage() {
	printf("usage:\r\n");
	printf("miniDB w rid idx buf\r\n");
	printf("miniDB r rid idx\r\n");
	printf("miniDB ls\r\n");
}

int getInt(char* s, int* i) {
	if(!i) return -1;

	if(1 == sscanf(s, "0x%x", i)) {
		return 1;
	}

	return sscanf(s, "%d", i);
}

int main(int argc, char* argv[]) {
	mini_init("e:\imgs.bin");

	if (argc < 2) {
		usage();
		exit(-1);
	}
	int rid, idx;
	if ('r' == *argv[1]) {
		getInt(argv[2], &rid);
		getInt(argv[3], &idx);
		char* buf = 0;
		int len = 0;
		int rd = minidb_read(rid, idx, &buf, &len);
		int i = 0;
		printf("read ok. data len:%d\r\n", rd);
		while(i < rd) {
			if(isprint(buf[i])) {
				printf("%02X%c ", buf[i], buf[i]);
			} else {
				printf("%02X. ", buf[i], buf[i]);
			}
			i++;

			if (0 == (i % 4)) {
				printf(" ");
			}
			if(0 == (i % 16)) {
				printf("\r\n");
			}
		}
		free(buf);
		
	} else if ('w' == *argv[1]) {
		getInt(argv[2], &rid);
		getInt(argv[3], &idx);
		minidb_write(rid, idx, argv[4], strlen(argv[4]));
	} else if (0 == strcmp("ls", argv[1])) {
		return minidb_ls();
	} else {
		printf("err cmd.\r\n");
		usage();
	}
	return 0;
}